package com.wenan.data
{
	import mx.collections.ArrayList;
	import mx.collections.IList;
	import com.wenan.ui.controls.asMaps.NationalMap;
	
	public class ProvinceCollection
	{
		private var _map:NationalMap;
		private var _innerList:ArrayList = new ArrayList();
		
		public function ProvinceCollection(map:NationalMap)
		{
			this._map = map;
		}

		public function get map():NationalMap
		{
			return _map;
		}
		
		public function getList():IList
		{
			return _innerList;
		}
		
		public function get length():int
		{
			return _innerList.length;
		}
		
		public function getAt(index:int):Province
		{
			return _innerList.getItemAt(index) as Province;
		}
		
		public function getIndexByName(provinceName:String):int
		{
			for(var i:int=0;i<_innerList.length;i++)
			{
				var province:Province = _innerList.getItemAt(i) as Province;
				if (province.name == provinceName)
				{
					return i;
				}
			}
			return -1;
		}
		
		public function findByName(provinceName:String):Province
		{
			var index:int = getIndexByName(provinceName);
			if (index < 0)
			{
				return null;
			}
			return _innerList.getItemAt(index) as Province;
		}
		
		public function getByName(provinceName:String):Province
		{
			var province:Province = findByName(provinceName);
			if (province == null) 
			{
				throw new Error("无法找到名称为 \""+provinceName+"\" 的省区.");
			}
			return province;
		}
		
		public function add(province:Province):void
		{
			_innerList.addItem(province);	
			_map.addChild(province.sprite);
		}
		
		public function insert(index:int, province:Province):void
		{
			_innerList.addItemAt(province, index);	
			_map.addChild(province.sprite);
		}
		
		public function remove(province:Province):void
		{
			_innerList.removeItem(province);
			_map.removeChild(province.sprite);
		}
		
		public function removeAt(index:int):void
		{
			var province:Province = _innerList.getItemAt(index) as Province;
			_innerList.removeItemAt(index);	
			_map.removeChild(province.sprite);
		}
		
		public function clear():void
		{
			for each(var province:Province in _innerList)
			{
				_map.removeChild(province.sprite);
			}
			_innerList.removeAll();
		}
		
		public function toArray():Array
		{
			return _innerList.toArray();
		}
	}
}